<?php

namespace App\Http\Controllers\file;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class UploadController extends Controller
{
    public function image(Request $request)
    {
        if (!$request->hasFile('file')) {
            return response()->json(['code' => 400, 'msg' => '没有上传文件']);
        }

        $file = $request->file('file');

        if (!$file->isValid()) {
            return response()->json(['code' => 400, 'msg' => '上传文件无效']);
        }
        // 获取 Dcat Admin 上传配置
        $disk = config('admin.upload.disk', 'public');
        $imageDir = config('admin.upload.directory.image', 'images');
        $ext = strtolower($file->getClientOriginalExtension());
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if (!in_array($ext, $allowed)) {
            return response()->json(['code' => 400, 'msg' => '图片格式不支持']);
        }
        // 存储路径（按日期）
        $path = $imageDir . '/' . date('Y/m/d');
        $filename = Str::random(20) . '.' . $ext;
        // 保存到和 Dcat 一样的磁盘 & 目录
        $file->storeAs($path, $filename, $disk);
        // 获取 URL（和 Dcat 一样）
        $url = Storage::disk($disk)->url($path . '/' . $filename);
        return $this->success($path . '/' . $filename);
    }
}
